/*
 * Copyright (c) 2001 Sun Microsystems, Inc.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *       Sun Microsystems, Inc. for Project JXTA."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact Project JXTA at http://www.jxta.org.
 *
 * 5. Products derived from this software may not be called "JXTA",
 *    nor may "JXTA" appear in their name, without prior written
 *    permission of Sun.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of Project JXTA.  For more
 * information on Project JXTA, please see
 * <http://www.jxta.org/>.
 *
 * This license is based on the BSD license adopted by the Apache Foundation.
 *
 * $Id: ContentManagerImpl.java,v 1.11 2002/11/04 02:02:00 lomax Exp $
 *
 */

package net.jxta.share;

import java.util.Vector;
import java.util.Enumeration;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;

import net.jxta.share.metadata.ContentMetadata;

/*
 * ContentManager implementation for managing local shared content within
 * a peer.
 */
public class ContentManagerImpl extends ContentManager {

    private Vector shares;	// shared Content objects
    private File sharesFile;	// shares index file
    private MimeTable mtab;	// mime type table

    private CMS cms = null;

    // name of shares index file
    private static final String SHARES_SER = "shares.ser";
    // name of mime type properties file
    private static final String MIME_PROPERTIES = "mime.properties";


    /*
     * Creates a new ContentManagerImpl using the specified directory.
     * If a shares index file already exists in the directory then
     * it will be restored. Otherwise, a new one will be created
     * and updated each time the index has been changed. If there
     * is a mime properties file then that will also be loaded
     * and can be used to determine a default mime type when none
     * is provided.
     */
    public ContentManagerImpl(File dir) throws IOException {
	this (dir, null);
    }
    /*
     * Creates a new ContentManagerImpl using the specified directory.
     * If a shares index file already exists in the directory then
     * it will be restored. Otherwise, a new one will be created
     * and updated each time the index has been changed. If there
     * is a mime properties file then that will also be loaded
     * and can be used to determine a default mime type when none
     * is provided.
     */
    public ContentManagerImpl(File dir, CMS cms) throws IOException {

	if (!dir.isDirectory()) {
	    throw new IOException("Directory not found: " + dir);
	}

	sharesFile = new File(dir, SHARES_SER);
	if (sharesFile.isFile()) {
	    load(sharesFile);
	} else {
	    shares = new Vector();
	}
	File f = new File(dir, MIME_PROPERTIES);
	if (f.isFile()) {
	    InputStream is = new BufferedInputStream(new FileInputStream(f));
	    mtab = new MimeTable();
	    mtab.load(is);
	    is.close();
	} else {
	    mtab = MimeTable.getDefaultMimeTable();
	}
	this.cms = cms;
    }

    /**
     * Shares the specified file.
     */
    public FileContent share(File file, String name, String type, String desc)
	throws IOException
    {
	if (name == null) {
	    name = file.getName();
	}
	FileContent fc = new FileContentImpl(file, name, type, desc);
	share(fc);
	return fc;
    }
    
    public FileContent share(File file, String name, String type, ContentMetadata[] metadata) throws IOException
    {
	if (name == null) {
	    name = file.getName();
	}

	FileContent fc = new FileContentImpl(file, name, type, metadata);
	share(fc);
	return fc;
    }

    // shares the specified Content object
    private void share(Content c) throws IOException {
	synchronized (this) {

	    if (cms != null) {
		// Index the new shared content.
		cms.publishContent (c);
	    }

	    shares.addElement(c);

	    try {
		save(sharesFile);
	    } catch (IOException e) {
		// if there was an error while trying to save the new index
		// then restore the original
		shares.removeElement(c);
		throw e;
	    }
	}
    }

    /**
     * Unshares the specified Content object.
     */
    public void unshare(Content c) throws IOException {
	synchronized (this) {
	    if (!shares.removeElement(c)) {
		throw new IllegalArgumentException("Content not shared");
	    }

	    if (cms != null) {
		// remove index the new shared content.
		cms.forgetContent (c);
	    }

	    try {
		save(sharesFile);
	    } catch (IOException e) {
		// if there was an error while trying to save the new index
		// then restore the original
		shares.addElement(c);
	    }
	}
    }

    /**
     * Unshares the specified Content object.
     * This hopefully will get deprecated soon.
     */ 
    public void unshare(ContentAdvertisement cAdv ) throws IOException {

        // search for the content based on content advertisement
	int i = -1;	
	for ( i = 0; i < shares.size(); i++ ) {
	    Content content = ( Content )shares.elementAt ( i );
	    if ( cAdv.getContentId().equals ( 
		     content.getContentAdvertisement().getContentId())) {
	        unshare ( ( Content )shares.elementAt( i ) );
	        return;
	    }
	}
    }


    /**
     * Returns all the shared Content.
     */
    public Content[] getContent() {
	synchronized (this) {
	    Content[] cs = new Content[shares.size()];
	    shares.copyInto(cs);
	    return cs;
	}
    }

    /**
     * Returns all the shared Content for the specified content id.
     */
    public Content[] getContent(ContentId id) {
	Vector v = new Vector();
	synchronized (this) {
	    Enumeration e = shares.elements();
	    while (e.hasMoreElements()) {
		Content c = (Content)e.nextElement();
		ContentAdvertisement ca = c.getContentAdvertisement();
		if (id.equals(ca.getContentId())) {
		    v.addElement(c);
		}
	    }
	}
	Content[] cs = new Content[v.size()];
	v.copyInto(cs);
	return cs;
    }

    /**
     * Returns all the shared Content accepted by the specified ContentFilter.
     */
    public Content[] getContent(ContentFilter cf) {
	Vector v = new Vector();
	synchronized (shares) {
	    Enumeration e = shares.elements();
	    while (e.hasMoreElements()) {
		Content c = (Content)e.nextElement();
		if (cf.accept(c)) {
		    v.addElement(c);
		}
	    }
	}
	Content[] cs = new Content[v.size()];
	v.copyInto(cs);
	return cs;
    }

    /**
     * Returns the mime type of the specified file, or null if unknown.
     */
    public String getMimeType(File file) {
	// Downshift to match Mime file type extension table.
	MimeInfo mi = mtab.getForName(file.getName().toLowerCase());
	return mi != null ? mi.getType() : null;
    }

    // saves content index to file
    private void save(File file) throws IOException {
	File tmp = tmpFile(file);
	FileOutputStream os = new FileOutputStream(tmp);
	try {
	    ObjectOutputStream oos = new ObjectOutputStream(os);
	    oos.writeObject(shares);
	    oos.close();
	} catch (IOException e) {
	    os.close();
	    tmp.delete();
	    throw e;
	}
	file.delete();
	if (!tmp.renameTo(file)) {
	    throw new IOException("Could not rename file: " + tmp);
	}
    }   
    
    // loads content index from file
    private void load(File file) throws IOException {
	FileInputStream is = new FileInputStream(file);
	try {
	    ObjectInputStream ois = new ObjectInputStream(is);
	    shares = (Vector)ois.readObject();
	    ois.close();
            checkSharedFiles (shares);
	} catch (IOException e) {
	    is.close();
	    throw e;
	} catch (ClassNotFoundException e) {
	    e.printStackTrace();
	    throw new InternalError();
	}
    }

    // Check to see if the [File]Content stored into the shares Vector still points to an uncorrupt file.
    private void checkSharedFiles (Vector shares) {
        Enumeration contentEnum = shares.elements();
        File sharedFile;
        FileContent sharedFileContent;
        long fileSize;
        boolean isCorrupted;
        while (contentEnum.hasMoreElements()) {
            Content content =(Content)contentEnum.nextElement();
            isCorrupted=false;
            if (content instanceof FileContent) {
                sharedFileContent=(FileContent) content;
                sharedFile = sharedFileContent.getFile();
                if (! sharedFile.exists()) {
                    //System.err.println ("File: " +content.getContentAdvertisement().getName()+ "Does not exist anymore, Unsharing it ...");
                    isCorrupted=true;
                }
                 else if (! sharedFile.canRead()) {
                    //System.err.println ("File: " +content.getContentAdvertisement().getName()+ "can't be read anymore, Unsharing it ...");
                    isCorrupted=true;
                }
                 else if (sharedFile.length()!=content.getContentAdvertisement().getLength()) {
                    //System.err.println ("File size for: " +content.getContentAdvertisement().getName()+ "has changed: Was "+content.getContentAdvertisement().getLength()+" bytes and now is: "+sharedFile.length()+" bytes. Unsharing it ...");
                    isCorrupted=true;
                }
                if (isCorrupted) {
                    try {
                        unshare(content);
                    }
                    catch (java.io.IOException e) {
                        System.err.println ("Can't unshare: " +content.getContentAdvertisement().getName()+" ...");
                    }
                }
            }
        }
    } // End checkSharedFiles Method

    // generate temp file name
    private static File tmpFile(File file) {
	return new File(file.getPath() + ".tmp");
    }
}





